﻿using Hangfire;
using Quartz;
using System;
using System.Threading.Tasks;
using Zocono.Infrastructure.Common;
using Zocono.WCS.Domain.WcsGetWmsJobDomain;

namespace Zocono.WCS.HangfireHost.TaskJobs
{
    public class GetScWorkTaskToMeJob
    {
        private readonly IWcsGetWmsJobService _wcsGetWmsJobService;
        private readonly ILogUtil _logUtil;
        private readonly TaskLock _taskLock;

        public GetScWorkTaskToMeJob(IWcsGetWmsJobService wcsGetWmsJobService,
            ILogUtil logUtil,
            TaskLock taskLock)
        {
            _wcsGetWmsJobService = wcsGetWmsJobService;
            _logUtil = logUtil;
            _taskLock = taskLock;
        }

        /// <summary>
        /// 执行作业任务
        /// </summary>
        /// <returns></returns>
        public async Task DoJob()
        {
            if (_taskLock.GetScTaskLock)
            {
                return;
            }
            try
            {
                _taskLock.GetScTaskLock = true;
                //定时读取堆垛机未执行任务到内存
                await _wcsGetWmsJobService.GetInitWorkTaskToMemory();
            }
            catch (Exception ex)
            {
                _logUtil.Error($"初始化堆垛机任务到内存作业报错ex={ex}");
            }
            finally
            {
                _taskLock.GetScTaskLock = false;
                _logUtil.Debug("初始化堆垛机任务到内存作业.....");
            }
        }

        /// <summary>
        /// 使用hangfire时调用
        /// </summary>
        /// <returns></returns>
        [AutomaticRetry(Attempts = 0)]
        public async Task HangfireJob()
        {
            await DoJob();
        }
    }
}
